import MobX, {observable as o, computed as c, action as a} from 'mobx';
import _ from 'lodash';
import axios from 'core/axios';
import RootStore from 'core/Store.js';
import request from 'core/request.js';
import Im from 'immutable';
import {browserHistory} from 'react-router';

class Store extends RootStore {
    constructor(args) {
        super(args);
    }

    will() {

    }

    @o visible = false;
    @o detail = {
        id: '',
        name: '',
        showId: '',
        sort: null,
        type: 1,
        url: '',
    };
    @o display = 'edit';
    @o isUpdateCover = false;//是否修改了封面
    @o coverFile = '';//base64生成的文件-->banner文件
    @o typeHasChange = false;//判断类型是否改变了

    @a
    setToDefault() {
        this.visible = false;
        this.detail.id = '';
        this.detail.name = '';
        this.detail.showId = '';
        this.detail.sort = null;
        this.detail.type = 1;
        this.detail.url = '';
        this.display = 'edit';
        this.isUpdateCover = false;
        this.coverFile = '';
        this.typeHasChange = false;
    }

    //关闭窗口
    @a
    closeDialog(e) {
        e.preventDefault();
        e.stopPropagation();
        this.visible = false;
        this.setToDefault();
    }

    @a
    bannerNameInput(v) {
        this.detail.name = v || '';
    }

    @a
    typeChange(v) {
        if(v.value !== this.detail.type){
            this.detail.type = v.value;
            this.detail.name = '';
            this.detail.showId = '';
            this.typeHasChange = true;
        }else{
            this.typeHasChange = false;
        }
    }

    sortChange(v) {
        this.detail.sort = v || '';
    }

    // idChange(v) {
    //     this.detail.showId = v || '';
    // }

    @a
    assignUserOnChange(v, id) {
        this.detail.name = v;
        this.detail.showId = id || '';
    }

    filesOnChange(e, refs) {
        e.preventDefault();
        let target = e.target;
        let files = target.files;
        this.isUpdateCover = true;
        this.coverFile = {
            thumb: URL.createObjectURL(files[0]),
            name: $$.utils.getFilename(files[0].name),
            file: files[0]
        };
        this.detail.url = this.coverFile.thumb;
        refs.value = '';
    }

    confirmInfo() {
        if (!this.detail.url) {
            this.stores.Message.fire('message', {type: $$.SEM.WARNING_TEXT, text: '请上传banner图'});
            return;
        };
        if (!this.detail.name || (!!this.detail.name && !this.detail.name.toString().trim())) {
            this.stores.Message.fire('message', {type: $$.SEM.WARNING_TEXT, text: '名称不能为空'});
            return;
        }
        if (!this.detail.showId || (!!this.detail.showId && !this.detail.showId.toString().trim())) {
            this.stores.Message.fire('message', {type: $$.SEM.WARNING_TEXT, text: 'id不能为空'});
            return;
        }
        if (this.isUpdateCover) {
            this.stores.Frame.showLoading();
            request({
                url: $$.api('getPolicy'),
                method: 'get',
                data: {type: 1}
            }).then((res) => {
                //上传需要相关数据
                var {
                    accessid,
                    callback,
                    dir,
                    expire,
                    host,
                    policy,
                    signature,
                    prefix,
                } = res.data;
                //遍历文件数据
                var file = this.coverFile.file;
                let formData = new FormData();
                let md5 = this.detail.name + Math.random() + '.' + this.coverFile.file.name.split('.').pop();
                console.log('md5',md5);
                formData.append('name', this.coverFile.file.name + Math.random());
                formData.append('key', encodeURI(dir + md5));
                formData.append('policy', policy);
                formData.append('OSSAccessKeyId', accessid);
                formData.append('success_action_status', '200');
                formData.append('callback', callback);
                formData.append('signature', signature);
                formData.append('file', file);
                //开始上传
                request({url: host, data: formData, method: 'post'}).then((uploadRes) => {
                    // this.uploadSuccessCover = uploadRes.data.data.modelCover;
                    if (uploadRes.code === $$.SEM.SUCCESS_CODE) {
                        this.updateInfo(uploadRes.data.modelCover);
                    } else {
                        this.stores.Frame.hideLoading();
                        this.stores.Message.fire('message', {
                            type: $$.SEM.ERROR_TEXT,
                            text: uploadRes.message
                        });
                    }
                }).catch((uploadErr) => {
                    this.stores.Frame.hideLoading();
                    this.stores.Message.fire('message', {
                        type: $$.SEM.ERROR_TEXT,
                        text: uploadErr.message
                    });
                });
            }).catch(err => {
                this.stores.Frame.hideLoading();
                this.stores.Message.fire('message', {
                    type: $$.SEM.ERROR_TEXT,
                    text: err.message
                });
            });
        } else {
            this.updateInfo();
        }
    }

    updateInfo(cover) {
        this.stores.Frame.showLoading();
        request({
            url: this.display === 'edit' ? $$.api('getBannerUpdate') : $$.api('addBanner'),
            method: 'post',
            data: {
                id: this.detail.id || null,
                name: this.detail.name || null,
                showId: this.detail.showId || null,
                sort: this.detail.sort || null,
                type: this.detail.type || null,
                url: cover || null,
            }
        }).then(res => {
            this.stores.Message.fire('message', {
                type: $$.SEM.SUCCESS_TEXT,
                text: res.message
            });
            this.setToDefault();
            this.stores.Frame.hideLoading();
            this.stores.BannerManage.getBannerList(1, 20);
        }).catch(err => {
            this.stores.Frame.hideLoading();
            this.stores.Message.fire('message', {
                type: $$.SEM.ERROR_TEXT,
                text: err.message
            });
        })
    }

    mount() {
        this.on('BannerEdit:show', (data) => {
            this.display = data.display;
            if (this.display === 'edit') {
                let bannerMessage = data.detail;
                this.detail = {
                    ...MobX.toJS(data.detail),
                    id: bannerMessage.id || '',
                    name: bannerMessage.name || '',
                    showId: bannerMessage.showId || '',
                    sort: bannerMessage.sort || '',
                    type: bannerMessage.type || '',
                    url: bannerMessage.url || '',
                };
            }
            this.visible = true;
        });

        browserHistory.listen(() => {
            if (this.visible) {
                this.setToDefault()
            }
        });
    }

}

export default Store;